library(geofacet)        #for plotting geographical regions 
library(ggplot2)         #for data visualisation 
library(MetBrewer)       #for colour palettes
library(ragg)            #for saving data viz in png
library(showtext)        #for displaying fonts in data viz
library(tidyverse)       #for data-wrangling

##data-wrangling----
BrSenSwitch <- read.csv("BrSenSwitch.csv", sep = ";") %>%
               mutate(fusao = ifelse(is.na(fusao), 0, fusao)) %>%
               mutate(fissao = ifelse(is.na(fissao), 0, fissao)) %>%
               mutate(partido_novo = ifelse(is.na(partido_novo), 0, partido_novo)) %>%
               mutate(home_inverted = 1-home) %>%
               filter(partido_novo != 1,
                      fissao != 1) %>%
               mutate(to_be_elected = case_when(legislatura == 48 ~ 1,
                                                legislatura == 49 ~ 2,
                                                legislatura == 50 ~ 1,
                                                legislatura == 51 ~ 2,
                                                legislatura == 52 ~ 1,
                                                legislatura == 53 ~ 2,
                                                legislatura == 54 ~ 1,
                                                legislatura == 55 ~ 2,
                                                legislatura == 56 ~ 1))

double_renovation <- BrSenSwitch %>% filter(to_be_elected == 2) 
single_renovation <- BrSenSwitch %>% filter(to_be_elected == 1)

##fonts----
font_add(family = "regular", "Barlow Semi Condensed-Regular.ttf")
font_add(family = "bold", "BarlowSemiCondensed-SemiBold.ttf")
showtext_auto() 

##Visualisation-I----
elecperf <- BrSenSwitch %>%
            select(cardapio, party_str, state, legislatura) %>%
            group_by(state, legislatura) %>%
            unique() %>%
            mutate(cardapio = case_when(cardapio == "PMDB" ~ "MDB",
                                        cardapio == "PFL" ~ "DEM",
                                        T ~ cardapio)) %>%
            filter(cardapio %in% c("PT", "PSDB", "MDB", "DEM", "PSL")) %>%
            rename(Parties = cardapio)

elecperf %>% ggplot(aes(legislatura, party_str, colour = Parties)) +
             geom_line(linewidth = 1.0) +
             scale_colour_manual(values=c(PT="#a00000",PSDB="#0058aa",MDB="#33a336",DEM="#0599da",PSL="#1f3467"))+
             coord_cartesian(expand = T) +
             xlab("Legislature") + ylab("Vote Share") + 
             facet_geo(~state, grid = "br_states_grid1", scales = "free_x") +
             guides(fill = guide_legend(title = "Partidos")) +
             theme(plot.title=element_text(family="bold", hjust=0.5, vjust = 0.5, size=65, color="black"),
                   plot.title.position = "plot",
                   plot.subtitle = element_text(family="bold", size=40, hjust=0.5, color="black"),
                   plot.caption= element_text(family="bold", size=45, color="black"),
                   plot.caption.position = "plot",
                   ##Background
                   panel.border=element_blank(),
                   panel.grid.major = element_blank(),
                   panel.grid.minor = element_blank(),
                   plot.background = element_rect(fill = "white", linetype = 'blank'),
                   panel.background = element_rect(fill = "white"),
                   #Axes
                   axis.ticks.length=unit(0.15, "cm"),
                   axis.ticks = element_blank(),
                   axis.line = element_blank(),
                   axis.title = element_text(size=55, family="bold", color="black"),
                   axis.text.y = element_text(size=40, family="regular", color="black"),
                   axis.text.x = element_text(size=40, family="regular", color="black"),
                   #multi-plot 
                   strip.text = element_text(family="regular", size=45, color="white"),
                   strip.background = element_rect(fill= "black"),
                   panel.spacing = unit(2, "lines"),
                   #Legend
                   legend.position = "top",
                   legend.text = element_text(family="regular",size=55),
                   legend.background = element_rect(fill = "white"),
                   legend.key = element_rect(fill = "white"),
                   legend.title = element_text(size = 60, family = "bold"),
                   legend.key.height = unit(1.5, "cm")) -> mar


ggsave("SuppMat.2.png",
       plot=mar,
       device = agg_png(width = 12, height = 14, units = "in", res = 300))


##Visualisation-II----
elec_comp <- read.csv("elec_comp.csv", sep = ";") %>%
             extract(st_leg_id, into = "state", regex = "([A-Z]+)\\d+") %>%
             select(state, ano, elec_comp)

elec_comp %>% ggplot(aes(ano, elec_comp)) +
              geom_line(linewidth = 1.0) +
              scale_y_continuous(limits = c(0, 1),
                                 breaks = seq(0, 1, by = 0.2)) +
              #coord_cartesian(expand = F) +
              xlab("") + ylab("Electoral Competition Index") + 
              facet_geo(~state, grid = "br_states_grid1") +
              labs(title = "",
                   subtitle = "",
                   caption = "") +
              theme(plot.title=element_text(family="bold", hjust=0.5, vjust = 0.5, size=65, color="black"),
                    plot.title.position = "plot",
                    plot.subtitle = element_text(family="bold", size=40, hjust=0.5, color="black"),
                    plot.caption= element_text(family="bold", size=45, color="black"),
                    plot.caption.position = "plot",
                    ##Background
                    panel.border=element_blank(),
                    panel.grid.major = element_blank(),
                    panel.grid.minor = element_blank(),
                    plot.background = element_rect(fill = "white", linetype = 'blank'),
                    panel.background = element_rect(fill = "white"),
                    #plot.margin=ggplot2::margin(0.5, 0.5, 0.5, 0.5, "in"),
                    #Axes
                    axis.ticks.length=unit(0.15, "cm"),
                    axis.ticks = element_blank(),
                    axis.line = element_blank(),
                    axis.title = element_text(size=60, family="bold", color="black"),
                    axis.text.y = element_text(size=35, family="regular", color="black"),
                    axis.text.x = element_text(size=35, family="regular", color="black"),
                    #multi-plot 
                    strip.text = element_text(family="regular", size=45, color="white"),
                    strip.background = element_rect(fill= "black"),
                    panel.spacing = unit(2, "lines")) -> sen_bra


ggsave("SuppMat.3.png",
       plot=sen_bra,
       device = agg_png(width = 12, height = 14, units = "in", res = 300))
